const prisma = require('../config/database');
const { Prisma } = require('@prisma/client');
const moment = require('moment-timezone');


// 获取分页考试数据
exports.getExamList = async (req, res) => {
  try {

    // 获取查询参数
    const userId = req.query.userId;
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const timeOrder = req.query.timeOrder || 'desc'; // 默认时间降序
    const reviewStatus = req.query.reviewStatus || '所有状态'; // 默认所有状态

    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: userId',
        data: null
      });
    }

    // 1. 获取用户对应的学科ID
    const userSubjects = await prisma.teacher_classes_subject.findMany({
      where: { teacher_id: parseInt(userId) },
      select: { subject_id: true }
    });

    const subjectIds = [...new Set(userSubjects.map(item => item.subject_id))];

    if (subjectIds.length === 0) {
      return res.status(200).json({
        code: 200,
        message: '获取考试列表成功',
        data: {
          list: [],
          total: 0
        }
      });
    }

    // 2. 获取所有考试，检查是否结束，更新状态
    const currentTimeFormat = moment.tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
    
  

    // 查找所有已结束但状态不是"待分配"的考试
    const finishedExams = await prisma.examination.findMany({
      where: { 
        end_time: { lt: new Date(currentTimeFormat) },
        examination_status: { notIn: ['待分配', '批阅中', '已批阅'] }
      }
    });

    // 更新这些考试的状态为"待分配"
    for (const exam of finishedExams) {
      await prisma.examination.update({
        where: { id: exam.id },
        data: { examination_status: '待分配' }
      });
    }

    // 检查所有"批阅中"状态的考试，更新已完成的考试状态
    const examsInReview = await prisma.examination.findMany({
      where: { examination_status: '批阅中' },
      select: { id: true }
    });
    
    // 对每个批阅中的考试检查其任务状态
    for (const exam of examsInReview) {
      // 获取该考试的所有批阅任务
      const reviewAssignments = await prisma.review_assignment.findMany({
        where: { examination_id: exam.id },
        select: { id: true, status: true }
      });
      
      // 如果没有任务，跳过
      if (reviewAssignments.length === 0) continue;
      
      // 检查是否所有任务都是已完成状态(status=3)
      const allCompleted = reviewAssignments.every(assignment => assignment.status === 3);
      
      // 如果所有任务都已完成，更新考试状态为"已批阅"
      if (allCompleted) {
        await prisma.examination.update({
          where: { id: exam.id },
          data: { examination_status: '已批阅' }
        });
      }
    }

    // 计算分页起始位置
    const skip = (page - 1) * pageSize;

    // 构建查询条件
    const where = {
      subject_id: { in: subjectIds } // 根据用户所教学科过滤考试
    };
    
    // 如果不是查询所有状态，添加批阅状态筛选条件
    if (reviewStatus !== '所有状态') {
      where.examination_status = reviewStatus;
    } else {
      // 当查询"所有状态"时，只查找三种特定状态的考试
      where.examination_status = { in: ['待分配', '批阅中', '已批阅'] };
    }

    // 使用 Examination 模型
    const [exams, total] = await Promise.all([
      prisma.examination.findMany({
        where,
        select: {
          id: true,
          name: true,
          start_time: true,
          end_time: true,
          examination_status: true,
          subject_id: true,
        },
        orderBy: {
          start_time: timeOrder === 'asc' ? 'asc' : 'desc'
        },
        skip,
        take: pageSize
      }),
      prisma.examination.count({ where })
    ]);

    // 转换为小驼峰命名
    const formattedExams = exams.map(exam => ({
      id: exam.id,
      name: exam.name,
      startTime: exam.start_time,
      endTime: exam.end_time,
      examinationStatus: exam.examination_status,
      subjectId: exam.subject_id
    }));

    // 返回结果
    res.status(200).json({
      code: 200,
      message: '获取考试列表成功',
      data: {
        list: formattedExams,
        total
      }
    });
  } catch (error) {
    console.error('获取考试列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取考试列表时出错: ' + error.message,
      data: null
    });
  }
}; 

// 获取特定学科的所有教师信息
exports.getTeachersBySubject = async (req, res) => {
  try {
    const { subjectId } = req.query;
    
    if (!subjectId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数：subjectId',
        data: null
      });
    }

    // 使用原生SQL查询
    // 先在teacher_classes_subject表中查询，然后连接user表获取教师信息
    const teachers = await prisma.$queryRaw`
      SELECT DISTINCT u.id, u.account, u.name
      FROM teacher_classes_subject tcs
      JOIN user u ON tcs.teacher_id = u.id
      WHERE tcs.subject_id = ${parseInt(subjectId)}
    `;

    // 返回结果
    res.status(200).json({
      code: 200,
      message: '获取教师列表成功',
      data: {
        list: teachers
      }
    });
  } catch (error) {
    console.error('获取教师列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取教师列表时出错: ' + error.message,
      data: null
    });
  }
}; 

// 分配批阅任务
exports.saveReviewSettings = async (req, res) => {
  
  try {
    const { 
      examId, 
      reviewers, 
      assignmentStrategy, 
      startTime, 
      endTime,
      enableReminder,
      remindHourBefore
    } = req.body;

    console.log('examId:', examId);
   

    // 参数验证
    if (!examId || !reviewers || !Array.isArray(reviewers) || reviewers.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数或参数格式错误',
        data: null
      });
    }

      // 查找该考试所有学生试卷
      const studentPapers = await prisma.student_paper.findMany({
        where: { examination_id: parseInt(examId) }
      });

      if (studentPapers.length === 0) {
        return res.status(404).json({
          code: 404,
          message: '没有找到相关的学生试卷',
          data: null
        });
      }
  
     


       // 事务处理，确保所有操作要么全部成功，要么全部失败
    await prisma.$transaction(async (prismaClient) => {
      // 分配策略1：按试卷分配
      if (parseInt(assignmentStrategy) === 1) {
        // 为每个批阅人员分配试卷
        const paperAssignments = distributeStudentPapers(studentPapers, reviewers);
        
      /*
        paperAssignments：
        {
        // 批阅人员id：试卷id数组
          1: [1, 2, 3],
          2: [4, 5, 6],
          3: [7, 8, 9]
        }
      */

        // 遍历所有批阅人员
        for (const reviewer of reviewers) {
          // 获取该批阅人员的试卷id数组
          const assignedPapers = paperAssignments[reviewer];
          
          if (assignedPapers && assignedPapers.length > 0) {
            // 创建批阅任务
            const reviewTask = await prismaClient.review_assignment.create({
              data: {
                examination_id: parseInt(examId),
                user_id: parseInt(reviewer),
                assignment_strategy: 1,
                start_time: new Date(startTime),
                end_time: new Date(endTime),
                status: 1, // 待批阅状态
                reminder_enabled: enableReminder ? 1 : 0,
                reminder_hours_before: enableReminder ? parseInt(remindHourBefore) : null,
                reminder_status: 0 // 未提醒状态
              }
            });
            
            createdTasks.push(reviewTask);

            // 获取分配试卷的所有主观题
            for (const paperId of assignedPapers) {
              // 查找该试卷中所有主观题的详情记录
              const subjectiveQuestions = await prismaClient.paper_detail.findMany({
                where: {
                  student_paper_id: paperId,
                  question_id: {
                    in: await prismaClient.question.findMany({
                      where: { answer_type_id: 2 }, // 2表示主观题
                      select: { id: true }
                    }).then(results => results.map(q => q.id))
                  }
                }
              });

              // 创建批阅任务详情
              for (const question of subjectiveQuestions) {
                const taskDetail = await prismaClient.review_assignment_detail.create({
                  data: {
                    review_assignment_id: reviewTask.id,
                    student_paper_id: paperId,
                    paper_detail_id: question.id,
                    status: 0 // 未完成批阅
                  }
                });
                
                createdTaskDetails.push(taskDetail);
              }
            }
          }
        }
      } 
      // 分配策略2：按单道主观题分配
      else if (parseInt(assignmentStrategy) === 2) {
        // 获取所有学生试卷的ID
        const paperIds = studentPapers.map(paper => paper.id);
        
        // 查找所有这些试卷中的主观题
        const allSubjectiveQuestions = await prismaClient.paper_detail.findMany({
          where: {
            student_paper_id: { in: paperIds },
            question_id: {
              in: await prismaClient.question.findMany({
                where: { answer_type_id: 2 }, // 主观题
                select: { id: true }
              }).then(results => results.map(q => q.id))
            }
          }
        });
       

        // 获取所有相关的问题信息
        const questionIds = [...new Set(allSubjectiveQuestions.map(q => q.question_id))];
        const questions = await prismaClient.question.findMany({
          where: {
            id: { in: questionIds }
          },
          select: {
            id: true,
            hard_level: true,
            question_type_id: true
          }
        });
        
        // 构建问题ID到问题信息的映射
        const questionMap = {};
        questions.forEach(q => {
          questionMap[q.id] = q;
        });
        
        // 为每个试卷题目添加问题信息
        const enhancedSubjectiveQuestions = allSubjectiveQuestions.map(q => ({
          ...q,
          question: questionMap[q.question_id] || {}
        }));

        console.log('enhancedSubjectiveQuestions:', enhancedSubjectiveQuestions);
         // 按题目序号分组
         const questionsByOrder = {};
         enhancedSubjectiveQuestions.forEach(q => {
           const key = q.question_order; 
           if (!questionsByOrder[key]) {
             questionsByOrder[key] = [];
           }
           questionsByOrder[key].push(q);
         });

        // 计算每个题目的批阅复杂度
        const orderComplexities = {};
        for (const [order, questions] of Object.entries(questionsByOrder)) {
          // 获取一个样本题来确定难度
          const sampleQuestion = questions[0];
          let complexity = 1; // 默认复杂度
          
          // 根据难度级别设置基础复杂度
          if (sampleQuestion.question.hard_level === '难') {
            complexity = 3; // 难题的复杂度为3
          } else if (sampleQuestion.question.hard_level === '中') {
            complexity = 2; // 中等难度题的复杂度为2
          } else if (sampleQuestion.question.hard_level === '易') {
            complexity = 1; // 简单题的复杂度为1
          }
          
        
          
          // 计算该题目的学生数量
          const studentCount = questions.length;
          
          // 总复杂度 = 单题复杂度 × 学生数量
          orderComplexities[order] = {
            order,
            complexity: complexity,
            totalComplexity: complexity * studentCount,
            studentCount: studentCount,
            hardLevel: sampleQuestion.question.hard_level,
            questionTypeId: sampleQuestion.question.question_type_id,
            questions: questions
          };
        }

          // 将题目按复杂度从高到低排序
          const sortedQuestionGroups = Object.values(orderComplexities).sort(
            (a, b) => b.totalComplexity - a.totalComplexity
          );

      
          
          // 统一的分配算法：无论题目数量与教师数量的关系如何
          const reviewerWorkloads = {};
          reviewers.forEach(reviewerId => {
            reviewerWorkloads[reviewerId] = {
              totalComplexity: 0,
              assignments: [] // 将保存分配的题目和学生范围
            };
          });

       // 针对每个题目序号，进行分配
       for (const questionGroup of sortedQuestionGroups) {
        const questions = questionGroup.questions;
        const complexity = questionGroup.complexity;
        const questionOrder = questionGroup.order;
        
        // 计算如何分配（决定是否分割）
        if (reviewers.length <= 1) {
          // 只有一个教师，直接全部分配
          const reviewerId = reviewers[0];
          reviewerWorkloads[reviewerId].totalComplexity += questionGroup.totalComplexity;
          reviewerWorkloads[reviewerId].assignments.push({
            questionOrder,
            startIndex: 0,
            endIndex: questions.length,
            questions: questions,
            complexity
          });
        } else {
          // 多个教师情况下，考虑分割
          
          // 评估当前题目的总复杂度与教师数量的关系
          // 如果题目复杂度很高或学生数量很多，考虑分给多位教师
          // 如果题目复杂度较低且学生少，考虑只分给一位教师
          
          // 计算给多少位教师
          let teacherCount = 1; // 默认分配给1位教师
          
          // 如果题目很复杂，考虑分给更多教师
          if (questionGroup.totalComplexity > 50 || questions.length > 50) {
              // 根据复杂度和学生数量动态决定教师数量
            teacherCount = Math.min(
              Math.ceil(questionGroup.totalComplexity / 10), // 基于复杂度
              Math.ceil(questions.length / 4),              // 基于学生数量
              reviewers.length                               // 不超过可用教师数
            );
          }
          
          // 按当前工作量排序教师（从低到高）
          const sortedReviewers = [...reviewers].sort((a, b) => 
            reviewerWorkloads[a].totalComplexity - reviewerWorkloads[b].totalComplexity
          );
          
          // 获取工作量最低的几位教师
          const selectedReviewers = sortedReviewers.slice(0, teacherCount);
          
          // 分割学生任务
          const studentsPerTeacher = Math.ceil(questions.length / teacherCount);
          
          // 为每位教师分配学生
          // 7个学生 2位老师  1个老师负责4个学生
          for (let i = 0; i < selectedReviewers.length; i++) {
            const reviewerId = selectedReviewers[i];
            const startIndex = i * studentsPerTeacher;
            const endIndex = Math.min((i + 1) * studentsPerTeacher, questions.length);
            
            // 如果没有学生可分配，跳过
            if (startIndex >= questions.length) {
              continue;
            }
            
            // 分配的题目与学生
            const assignedQuestions = questions.slice(startIndex, endIndex);
            const assignmentComplexity = complexity * assignedQuestions.length;
            
            // 更新教师工作量
            reviewerWorkloads[reviewerId].totalComplexity += assignmentComplexity;
            reviewerWorkloads[reviewerId].assignments.push({
              questionOrder,  
              startIndex,
              endIndex,
              questions: assignedQuestions,
              complexity,
              totalComplexity: assignmentComplexity
            });
          }
        }
      }


     // 创建批阅任务
        for (const reviewerId of reviewers) {
          const assignments = reviewerWorkloads[reviewerId].assignments;
          
          // 如果没有分配任何题目，跳过
          if (assignments.length === 0) {
            continue;
          }
          
          // 创建批阅任务
          const reviewTask = await prismaClient.review_assignment.create({
            data: {
              examination_id: parseInt(examId),
              user_id: parseInt(reviewerId),
              assignment_strategy: 2,
              start_time: new Date(startTime),
              end_time: new Date(endTime),
              status: 1, // 待批阅状态
              reminder_enabled: enableReminder ? 1 : 0,
              reminder_hours_before: enableReminder ? parseInt(remindHourBefore) : null,
              reminder_status: 0, // 未提醒状态
              total_complexity: reviewerWorkloads[reviewerId].totalComplexity // 添加总复杂度字段
            }
          });
          
          
          // 为教师分配具体的题目
          for (const assignment of assignments) {
            for (const question of assignment.questions) {
              const taskDetail = await prismaClient.review_assignment_detail.create({
                data: {
                  review_assignment_id: reviewTask.id,
                  student_paper_id: question.student_paper_id,
                  paper_detail_id: question.id,
                  status: 0 // 未完成批阅
                }
              });
         
            }
          }
      
        }

      }


      // 更新考试状态为"批阅中"
      await prismaClient.examination.update({
        where: { id: parseInt(examId) },
        data: { examination_status: '批阅中' }
      });
    });

    res.status(200).json({
      code: 200,
      message: '批阅任务分配成功',
      data: null
    });
    

  }catch(error){
    console.error('分配批阅任务失败:', error);
    res.status(500).json({
      code: 500,
      message: '分配批阅任务时出错: ' + error.message,
      data: null
    });
  }


}


// 辅助函数：分配学生试卷给批阅人员（平均分配）
/**
 * 
 * @param {*} papers 学生试卷数组
 * @param {*} reviewers 批阅人员数组
 * @returns 
 */
function distributeStudentPapers(papers, reviewers) {
  const distribution = {};
  reviewers.forEach(reviewer => {
    distribution[reviewer] = [];
  });
  
  // 平均分配试卷
  // 遍历所有试卷
  papers.forEach((paper, index) => {
    // 使用取模运算来确定每份试卷分配给哪个批阅人员，确保每个批阅人员分配到的试卷数量尽可能均匀
    // 使用 试卷数组的下标 取模 批阅人员数组的长度，得到批阅人员数组的下标
    const reviewerIndex = index % reviewers.length;
    // 获取批阅人员id
    const reviewerId = reviewers[reviewerIndex];
    // 将试卷id添加到批阅人员的试卷数组中
    distribution[reviewerId].push(paper.id);
  });
  
  return distribution;
}

// 获取某场考试的批阅进度
exports.getExamReviewProgress = async (req, res) => {
  try {
    const { examId } = req.query;
    
    // 参数验证
    if (!examId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: examId',
        success: false
      });
    }

    // 查询考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: parseInt(examId) }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        success: false
      });
    }

    // 查询该考试的所有批阅任务
    const reviewAssignments = await prisma.review_assignment.findMany({
      where: { examination_id: parseInt(examId) },
      select: {
        id: true,
        user_id: true,
        assignment_strategy: true,
        status: true,
        total_complexity: true
      }
    });

    // 如果没有分配任何批阅任务
    if (reviewAssignments.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        success: true,
        data: {
          list: [],
          total: 0,
          doneTotal: 0
        }
      });
    }

    // 判断批阅策略 (取第一个任务的策略，假设所有任务使用相同的策略)
    const assignmentStrategy = reviewAssignments[0].assignment_strategy;
    
    let total = 0;
    let doneTotal = 0;
    let teacherProgressList = [];

    // 按"整张试卷"分配批阅任务
    if (assignmentStrategy === 1) {
      // 获取学生试卷总数
      const studentPapers = await prisma.student_paper.findMany({
        where: { examination_id: parseInt(examId) }
      });
      total = studentPapers.length;

      // 统计每个教师的批阅进度
      for (const assignment of reviewAssignments) {
        // 获取教师信息
        const teacher = await prisma.user.findUnique({
          where: { id: assignment.user_id }
        });

        // 获取该教师分配到的试卷
        const assignmentDetails = await prisma.review_assignment_detail.findMany({
          where: { 
            review_assignment_id: assignment.id,
            student_paper_id: { not: null }
          },
          select: {
            student_paper_id: true,
            status: true
          }
        });

        // 获取不重复的学生试卷ID
        const uniquePaperIds = [...new Set(assignmentDetails.map(detail => detail.student_paper_id))];
        const detailCount = uniquePaperIds.length;

        // 计算该教师已完成批阅的试卷数量
        let doneCount = 0;
        for (const paperId of uniquePaperIds) {
          // 获取该试卷所有批阅详情
          const paperDetailStatuses = await prisma.review_assignment_detail.findMany({
            where: {
              review_assignment_id: assignment.id,
              student_paper_id: paperId
            },
            select: {
              status: true
            }
          });
          
          // 如果该试卷的所有批阅详情都已完成（status=1），则计入已完成数量
          if (paperDetailStatuses.length > 0 && paperDetailStatuses.every(detail => detail.status === 1)) {
            doneCount++;
            // 计入整体已完成数量（避免重复计算）
            if (!teacherProgressList.some(item => 
              item.teacherId === assignment.user_id && 
              item.paperIds && 
              item.paperIds.includes(paperId)
            )) {
              doneTotal++;
            }
          }
        }

        teacherProgressList.push({
          teacherId: assignment.user_id,
          teacherName: teacher ? teacher.name : '',
          teacherAccount: teacher ? teacher.account : '',
          detailCount,
          doneCount,
          paperIds: uniquePaperIds, // 用于后续去重，不会返回给前端
          totalComplexity: assignment.total_complexity || 0
        });
      }

      // 清理辅助字段
      teacherProgressList = teacherProgressList.map(({ paperIds, ...rest }) => rest);

    } 
    // 按"单道大题"分配批阅任务
    else if (assignmentStrategy === 2) {
      // 获取该考试所有学生试卷ID
      const studentPapers = await prisma.student_paper.findMany({
        where: { examination_id: parseInt(examId) },
        select: { id: true }
      });

      
      const paperIds = studentPapers.map(paper => paper.id);
      
      // 获取所有主观题的总数
      const subjectiveQuestionCount = await prisma.paper_detail.count({
        where: {
          student_paper_id: { in: paperIds },
          question_id: {
            in: await prisma.question.findMany({
              where: { answer_type_id: 2 }, // 假设2表示主观题
              select: { id: true }
            }).then(results => results.map(q => q.id))
          }
        }
      });
      
      total = subjectiveQuestionCount;
      
      // 统计每个教师的批阅进度
      for (const assignment of reviewAssignments) {
        // 获取教师信息
        const teacher = await prisma.user.findUnique({
          where: { id: assignment.user_id }
        });
        
        // 获取该教师分配到的试题详情数量
        const detailCount = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id,
            paper_detail_id: { not: null }
          }
        });
        
        // 获取该教师已完成批阅的试题数量
        const doneCount = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id,
            paper_detail_id: { not: null },
            status: 1
          }
        });
        
        teacherProgressList.push({
          teacherId: assignment.user_id,
          teacherName: teacher ? teacher.name : '',
          teacherAccount: teacher ? teacher.account : '',
          detailCount,
          doneCount,
          totalComplexity: assignment.total_complexity || 0
        });
        
        // 累加到总的已完成数量
        doneTotal += doneCount;
      }
    }

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list: teacherProgressList,
        total,
        doneTotal,
        assignmentStrategy
      }
    });
    
  } catch (error) {
    console.error('获取考试批阅进度失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试批阅进度失败',
      success: false,
      error: error.message
    });
  }
};

// 获取考试批阅详情
exports.getReviewDetail = async (req, res) => {
  try {
    const { examinationId } = req.query;
    
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: examinationId',
        data: null
      });
    }

    // 查询考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: parseInt(examinationId) }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 查询该考试的所有批阅任务
    const reviewAssignments = await prisma.review_assignment.findMany({
      where: { examination_id: parseInt(examinationId) },
      select: {
        id: true,
        user_id: true,
        assignment_strategy: true,
        status: true
      }
    });

    // 如果没有分配任何批阅任务
    if (reviewAssignments.length === 0) {
      return res.status(200).json({
        code: 200,
        message: '获取批阅详情成功',
        data: {
          assignmentStrategy: null,
          list: []
        }
      });
    }

    // 判断批阅策略
    const assignmentStrategy = reviewAssignments[0].assignment_strategy;
    
    const reviewDetailList = [];

    // 按"整张试卷"分配批阅任务
    if (assignmentStrategy === 1) {
      for (const assignment of reviewAssignments) {
        // 获取教师信息
        const teacher = await prisma.user.findUnique({
          where: { id: assignment.user_id }
        });

        if (!teacher) continue;

        // 获取该教师分配到的试卷
        const assignmentDetails = await prisma.review_assignment_detail.findMany({
          where: { 
            review_assignment_id: assignment.id
          },
          select: {
            student_paper_id: true,
            status: true
          }
        });

        // 获取不重复的学生试卷ID
        const uniquePaperIds = [...new Set(assignmentDetails.map(detail => detail.student_paper_id))];
        const total = uniquePaperIds.length;

        // 计算该教师已完成批阅的试卷数量
        let doneTotal = 0;
        for (const paperId of uniquePaperIds) {
          // 获取该试卷所有批阅详情
          const paperDetailStatuses = await prisma.review_assignment_detail.findMany({
            where: {
              review_assignment_id: assignment.id,
              student_paper_id: paperId
            },
            select: {
              status: true
            }
          });
          
          // 如果该试卷的所有批阅详情都已完成（status=1），则计入已完成数量
          if (paperDetailStatuses.length > 0 && paperDetailStatuses.every(detail => detail.status === 1)) {
            doneTotal++;
          }
        }

        reviewDetailList.push({
          teacherId: teacher.id,
          teacherAccount: teacher.account,
          teacherName: teacher.name,
          total,
          doneTotal
        });
      }
    } 
    // 按"单道大题"分配批阅任务
    else if (assignmentStrategy === 2) {
      for (const assignment of reviewAssignments) {
        // 获取教师信息
        const teacher = await prisma.user.findUnique({
          where: { id: assignment.user_id }
        });

        if (!teacher) continue;
        
        // 获取该教师分配到的试题详情数量
        const total = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id
          }
        });
        
        // 获取该教师已完成批阅的试题数量
        const doneTotal = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id,
            status: 1
          }
        });
        
        reviewDetailList.push({
          teacherId: teacher.id,
          teacherAccount: teacher.account,
          teacherName: teacher.name,
          total,
          doneTotal
        });
      }
    }

    return res.status(200).json({
      code: 200,
      message: '获取批阅详情成功',
      data: {
        assignmentStrategy,
        list: reviewDetailList
      }
    });
    
  } catch (error) {
    console.error('获取考试批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试批阅详情失败: ' + error.message,
      data: null
    });
  }
};

/**
 * 根据考试ID获取本场考试的所有主观题
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含主观题信息的数组
 */
exports.getSubjectiveByExamId = async (req, res) => {
  try {
    const { examinationId } = req.query;
    
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: examinationId',
        data: null
      });
    }

    // 查询考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: parseInt(examinationId) },
      select: {
        id: true,
        exam_plan_id: true
      }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    if (!examination.exam_plan_id) {
      return res.status(404).json({
        code: 404,
        message: '考试没有关联的组卷方案',
        data: null
      });
    }

    // 获取组卷方案的所有题目序号
    const examPlanDetails = await prisma.exam_plan_details.findMany({
      where: { exam_plan_id: examination.exam_plan_id },
      select: {
        question_order: true
      },
      orderBy: {
        question_order: 'asc'
      }
    });

    if (examPlanDetails.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: []
      });
    }

    // 获取该考试下学生的答题记录，筛选出主观题
    const studentPapers = await prisma.student_paper.findMany({
      where: { examination_id: parseInt(examinationId) },
      select: { id: true },
      take: 1 // 只需要一份学生试卷即可获取题目信息
    });

    if (studentPapers.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '没有找到相关的学生试卷',
        data: null
      });
    }

    const paperDetails = await prisma.paper_detail.findMany({
      where: {
        student_paper_id: studentPapers[0].id
      },
      select: {
        question_id: true,
        question_order: true
      },
      orderBy: {
        question_order: 'asc'
      }
    });

    if (paperDetails.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: []
      });
    }

    // 获取题目信息
    const questionIds = paperDetails.map(detail => detail.question_id);
    
    // 查询所有主观题
    // 先从answer_type表中查询主观题的ID
    const answerTypes = await prisma.answer_type.findMany({
      where: {
        name: { contains: '主观题' }
      },
      select: {
        id: true
      }
    });
    
    if (answerTypes.length === 0) {
      return res.status(500).json({
        code: 500,
        message: '未找到主观题类型',
        data: null
      });
    }
    
    const subjectiveTypeId = answerTypes[0].id;
    console.log('主观题类型ID:', subjectiveTypeId);
    
    // 使用查询到的主观题类型ID查询试题
    const questions = await prisma.question.findMany({
      where: {
        id: { in: questionIds },
        answer_type_id: subjectiveTypeId
      },
      select: {
        id: true,
        name: true,
        answer_id: true,
        question_content: true
      }
    });

    // 获取主观题的答案
    const answerIds = questions.map(q => q.answer_id).filter(id => id);
    
    const subjectiveAnswers = await prisma.subjective_answers.findMany({
      where: {
        id: { in: answerIds }
      },
      select: {
        id: true,
        reference_answer: true,
        grading_rules: true
      }
    });

    // 创建答案ID到答案信息的映射
    const answerMap = {};
    subjectiveAnswers.forEach(answer => {
      answerMap[answer.id] = {
        referenceAnswer: answer.reference_answer,
        gradingRules: answer.grading_rules
      };
    });

    // 创建题目ID到题号的映射
    const questionOrderMap = {};
    paperDetails.forEach(detail => {
      questionOrderMap[detail.question_id] = detail.question_order;
    });

    // 按照题目序号排序并格式化返回数据
    const subjectiveQuestions = questions.map(question => {
      const answerInfo = question.answer_id ? answerMap[question.answer_id] : {};
      return {
        questionId: question.id,
        questionOrder: questionOrderMap[question.id] || 0,
        questionName: question.name || '未命名题目',
        questionContent: question.question_content || '',
        answerId: question.answer_id || null,
        referenceAnswer: answerInfo?.referenceAnswer || '',
        gradingRules: answerInfo?.gradingRules || ''
      };
    });

    // 按题目序号排序
    subjectiveQuestions.sort((a, b) => a.questionOrder - b.questionOrder);

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: subjectiveQuestions
    });
  } catch (error) {
    console.error('获取考试主观题失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试主观题失败: ' + error.message,
      data: null
    });
  }
};

/**
 * 保存主观题评分细则
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回保存结果
 */
exports.saveSubject = async (req, res) => {
  try {
    const { answerId, gradingRules } = req.body;
    
    // 参数验证
    if (!answerId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: answerId',
        data: null
      });
    }

    // 查询答案是否存在
    const answer = await prisma.subjective_answers.findUnique({
      where: { id: parseInt(answerId) }
    });

    if (!answer) {
      return res.status(404).json({
        code: 404,
        message: '主观题答案不存在',
        data: null
      });
    }

    // 更新评分细则
    await prisma.subjective_answers.update({
      where: { id: parseInt(answerId) },
      data: { grading_rules: gradingRules }
    });

    return res.status(200).json({
      code: 200,
      message: '评分细则保存成功',
      data: null
    });
  } catch (error) {
    console.error('保存评分细则失败:', error);
    return res.status(500).json({
      code: 500,
      message: '保存评分细则失败: ' + error.message,
      data: null
    });
  }
};

